const Router = require('koa-router');

const router = new Router({
	prefix:'/rnApi'
});

const  db = require('../mongodb/rndb.js');
const AppInfo = db.RnAppInfo;
const UserInfo = db.RnUserInfo;

router.get('/',async(ctx,next)=>{
	await ctx.render('index',{
		title:"首页"
	})
});

router.post('/add_info',async(ctx,next)=>{
	var postData = ctx.request.body;
	var Info =new AppInfo(postData);
	try{
		await Info.save();
        ctx.status=200;
        ctx.body ={
           code:1,
           text:"发布成功"
         }
	} catch(e){
		console.log(e);
        ctx.body = "error";
	}
});
//获取所有文章
router.get('/get_all_info_time',async(ctx,next)=>{
	var allInfo;
    let fetch = function(){
        return new Promise(function (resolve, reject) {
            AppInfo.find({}).sort({likeNum : -1}).exec(function(err,data){
                if (err){
                    console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var allInfo = await fetch();
	ctx.status = 200;
    ctx.body = {
        code:1,
        data:allInfo
    };
});
//新加评论
router.post('/add_remark',async(ctx,next)=>{
    var postData = ctx.request.body;
    console.log(postData)
    var id = postData.id;
    var userId = postData.userId;
    var userName = postData.userName;
    var markContent = postData.markContent;
    var userIcon = postData.userIcon;
    var markList=[];
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.findById(id,function(err, res){
                if (err) {
                    console.log("Error:" + err);
                }else {
                    Info = res;
                    markList = Info.markList;
                    resolve(markList);
                }
            });
        });
    }
    var markList = await fetch(postData);
    var markInfo = {};
    markInfo.userName = userName;
    markInfo.userId = userId;
    markInfo.markContent = markContent;
    markInfo.userIcon = userIcon;
    markList.push(markInfo);
     //修改markNum
    var markNum = markList.length;
    var updataInfo = {'markNum':markNum,'markList':markList};
    let fetch2 = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.findByIdAndUpdate(id,updataInfo,function(err,data){
            if (err){
                console.log(err);
            }
                resolve("success");
            });
        });
    }
    var markList = await fetch2(postData);
    ctx.status = 200;
    console.log(markList)
    ctx.body = {
        code:1,
        data:markList
    };
});
//修改likeNum数（点赞）  ----文章id，评论id，用户id
router.post('/edit_like',async(ctx,next)=>{
    var postData = ctx.request.body;
    console.log(postData)
    var id = postData.id;
    var markId = postData.markId;
    var userId = postData.userId;
    var markList=[];
    var likeNum = 0;
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.findById(id,function(err, res){
                if (err) {
                    console.log("Error:" + err);
                } else{
                    Info = res;
                    markList = Info.markList;
                    resolve(markList);
                }
            });
        });
    }
    var markList = await fetch(postData);
    for(let i = 0;i<markList.length;i++){
        if(markList[i]._id == markId){
            likedList = markList[i].liked;
            var indexPos = likedList.indexOf(userId);
            if(indexPos==-1){
                likedList.push(userId);
            } else{
                likedList.splice(indexPos,1);
            };
            markList[i].liked =likedList;
            markList[i].like = likedList.length;
        }
        likeNum = likeNum+markList[i].like;
    }
    var updatalikeNum = {'likeNum':likeNum,'markList':markList};
    var fetch2 = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.findByIdAndUpdate(id,updatalikeNum,function(err,data){
                if (err){
                  console.log(err);
                }
                resolve('success');
            });
        });
    }
    var markList = await fetch2(postData);
    ctx.status = 200;
	ctx.body = {
        code:1,
        data:markList
    }
});
//传id查询      ----id
router.get('/get_info_byId',async(ctx,next)=>{
    var postData = ctx.request.query;
    var id = postData.id;
	var fetch = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.find({_id:id},function(err,data){
                if (err){
                    console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var allInfo = await fetch(postData);
    ctx.status = 200;
	ctx.body = allInfo;
});

//传tag查询      ----tag
router.get('/get_info_bytag',async(ctx,next)=>{
    var postData = ctx.request.query;
    var tag = postData.tag;
    var allInfo=[];
    var fetch = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.find({tag:tag},function(err,data){
                if (err){
                    console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var allInfo = await fetch(postData);
    ctx.status = 200;
    ctx.body = allInfo;
});

//查询某个人下的所有提问      ----用户id
router.get('/get_info_byUser',async(ctx,next)=>{
    var postData = ctx.request.query;
    var authorId = postData.authorId;
    var allInfo;
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            AppInfo.find({'authorId':params.authorId},function(err,data){
                if (err){
                    console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var allInfo = await fetch(postData);
    ctx.status = 200;
    ctx.body ={
        code:1,
        data:allInfo
    }
});

//查看我评论过的  ----用户id
router.get('/get_mark_content',async(ctx,next)=>{
    var postData = ctx.request.query;
    var userId = postData.id;
    var markedList=[];
	let fetch = function(){
        return new Promise(function (resolve, reject) {
            AppInfo.find({},function(err, res){
                if (err) {
                    console.log("Error:" + err);
                }
                else {
                    InfoList = res;
                    resolve(InfoList);
                }
            });
        });
    }
    var InfoList = await fetch();
	InfoList.forEach(function(item){
		item.markList.forEach(function(mark){
            for(var key in mark){
                if(key=='userId'){
                    if(mark['userId'] == userId){
                        if(markedList.indexOf(item)==-1){
                            markedList.push(item);
                        }
                    }
                }
            };
		})
	});
    console.log(markedList)
    ctx.status = 200;
    ctx.body = markedList;
});
//查看所有标签
router.get('/get_tags',async(ctx,next)=>{
    var TagList=[];
    var InfoList=[];
    let fetch = function(){
        return new Promise(function (resolve, reject) {
            AppInfo.find({},function(err, res){
                if (err) {
                    console.log("Error:" + err);
                }
                else {
                    InfoList = res;
                    for(let i=0;i<InfoList.length;i++){
                      if(TagList.indexOf(InfoList[i].tag)==-1){
                          TagList.push(InfoList[i].tag);
                       }
                    }
                    resolve(TagList);
                }
            });
        });
    }
    var TagList = await fetch();
    ctx.status = 200;
    ctx.body = TagList;
});


//注册新用户
router.post('/add_user',async(ctx,next)=>{
    var postData = ctx.request.body;
    var id = postData.user;
    let fetch = function(params){
       return new Promise(function (resolve, reject) {
          UserInfo.find({'user':params.user},function(err,data){
          if (err){
            console.log(err);
          }
          resolve(data);
        });
      })
    }
    var allInfo = await fetch(postData);
    console.log(allInfo)
    if(allInfo.length!=0){
      console.log("用户名已注册")
      ctx.status = 200;
      ctx.statusText = "用户名已注册";
      ctx.body = {
        code:2,
        text:"用户名已注册"
      };
    }else{
       console.log("注册成功")
        ctx.status = 200;
        var Info =new UserInfo(postData);
        try{
          await Info.save();
          ctx.body = {
            code:1,
            text:"注册成功"
          };
        } catch(e){
          ctx.body = {
            code:2,
            text:"发生错误"
          };
        }
    }
});
//用户登陆
router.get('/user_login',async(ctx,next)=>{
  var postData = ctx.request.query;
  let fetch = function(params){
       return new Promise(function (resolve, reject) {
          UserInfo.find({'user':params.user},function(err,data){
          if (err){
            console.log(err);
          }
          resolve(data);
        });
      })
  }
  var allInfo = await fetch(postData);
  if(allInfo.length==0){
      console.log("用户未注册")
      ctx.status = 200;
      ctx.body = {
        code:2,
        text:"用户未注册"
      };
      return;
    }
    if(postData.password==allInfo[0].password){
      ctx.status = 200;
      ctx.body = {
        code:1,
        text:"登录成功"
      };
    }else{
      ctx.status = 200;
      ctx.body = {
        code:2,
        text:"密码错误"
      };
    }
});
//修改密码
router.post('/edit_password',async(ctx,next)=>{
    var postData = ctx.request.body;
    var id = postData.user;
    var allInfo=[];
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            UserInfo.find({'user':id},function(err,data){
                if (err){
                   console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var InfoList = await fetch(postData);
      if(allInfo.length==0){
        ctx.status = 200;
        ctx.body = {
          code:2,
          text:"用户未注册"
        };
      }else if(InfoList[0].password !=postData.password){
          ctx.status = 200;
          ctx.body = {
            code:2,
            text:"原密码输入有误"
          };
      }else{
        var updataData={'password': postData.newpassword};
        let fetch2 = function(params){
            return new Promise(function (resolve, reject) {
                UserInfo.findByIdAndUpdate({'_id':InfoList[0]._id},updataData,function(err,data){
                    if (err){
                        console.log(err);
                    }
                    resolve("success");
                });
            });
        }
        var flag = await fetch2(postData);
        ctx.status = 200;
        ctx.body = {
            code:1,
            text:"修改成功"
        };
      }
});
//修改icon
router.post('/edit_icon',async(ctx,next)=>{
    var postData = ctx.request.body;
    var id = postData.user;
    var allInfo=[];
    var updataData={'icon': postData.icon};
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            UserInfo.find({'user':id},function(err,data){
                if (err){
                   console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            });
        });
    }
    var InfoList = await fetch(postData);
    let fetch2 = function(){
        return new Promise(function (resolve, reject) {
            UserInfo.findByIdAndUpdate({'_id':InfoList[0]._id},updataData,function(err,data){
                if (err){
                    console.log(err);
                }
                resolve("success");
            });
        });
    }
    var InfoList = await fetch2();
    ctx.status = 200;
    ctx.body = {
        code:1,
        text:"修改成功"
    };
});
//个人中心
router.get('/person_center',async(ctx,next)=>{
    var postData = ctx.request.query;
    var Sum=0;
    let fetch = function(params){
        return new Promise(function (resolve, reject) {
            UserInfo.find({'user':postData.user},function(err,data){
                if (err){
                  console.log(err);
                }
                allInfo = data;
                resolve(allInfo);
            })
        });
    }
    var allInfo = await fetch(postData);
    let fetch2 = function(){
        return new Promise(function (resolve, reject) {
            AppInfo.find({},function(err, res){
                if (err) {
                    console.log("Error:" + err);
                }
                else {
                    InfoList = res;
                    resolve(InfoList);
                }
            });
        });
    }
    var InfoList = await fetch2();
    InfoList.forEach(function(item){
        item.markList.forEach(function(mark){
            for(var key in mark){
                if(key=='userId'){
                    if(mark['userId'] == postData.user){
                       Sum=Sum+mark['like']
                    }
                }
            };
        })
    });
    ctx.status = 200;
    ctx.body = {
        code:1,
        likeSum:Sum,
        data:allInfo
    };
});

module.exports = router;